#include "CadHeaderParser.h"

#include "UnitsParser.h"
#include "SpecParser.h"
#include "ChangeRecParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

CadHeaderParser::CadHeaderParser(
    UnitsParser *&_unitsParser
    , SpecParser *&_specParser
    , ChangeRecParser *&_changeRecParser
):    m_unitsParser(_unitsParser)
    , m_specParser(_specParser)
    , m_changeRecParser(_changeRecParser)
{

}

bool CadHeaderParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new CadHeader());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("units")))
    {
        data = reader->attributes().value(QStringLiteral("units"));
        if (!m_unitsParser->parse(reader, data))
            return false;
        m_result->units = m_unitsParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("units: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("Spec"))
        {
            if (!m_specParser->parse(reader))
                return false;
            auto result = m_specParser->result();
            m_result->specList.append(result);
        }
        else if (name == QStringLiteral("ChangeRec"))
        {
            if (!m_changeRecParser->parse(reader))
                return false;
            auto result = m_changeRecParser->result();
            m_result->changeRecList.append(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

CadHeader *CadHeaderParser::result()
{
    return m_result.take();
}

}